package com.itheima.leetcode;

/**
 * 根据值删除节点
 *
 * @FileName E02LeetCode203
 * @Description
 * @Author Sword
 * @date 2025-03-19
 **/
public class E02LeetCode203 {

    /*public static ListNode removeElements(ListNode head, int value) {
        ListNode s = new ListNode(-1, head);
        ListNode p1 = s;
        ListNode p2 = s.next;   //ListNode p2 = p1.next;
        while (p2 != null) {
            if (p2.val == value) {
                //删除，p2向后平移
                p1.next = p2.next;
                //p2 = p1.next;
            } else {
                //p1,p2向后平移
                p1 = p1.next;
                //p2 = p1.next;
            }
            p2 = p2.next;
        }
        return s.next;
    }*/

    //方法一
    /*public static ListNode removeElements(ListNode head, int value) {
        ListNode s = new ListNode(-1, head);
        ListNode p1 = s;
        ListNode p2;
        while ((p2 = p1.next) != null) {
            if (p2.val == value) {
                //删除，p2向后平移
                p1.next = p2.next;
            } else {
                //p1,p2向后平移
                p1 = p1.next;
            }
        }
        return s.next;
    }*/

    //方法二
    public static ListNode removeElements(ListNode p, int value) {
        if (p != null) {
            return null;
        }

        if (p.val == value) {
            return removeElements(p.next, value);
        } else {
            p.next = removeElements(p.next, value);
            return p;
        }
    }

    public static void main(String[] args) {
        /*ListNode head = ListNode.of(1, 2, 6, 3, 6);
        System.out.println(head);
        ListNode listNode = removeElements(head, 6);
        System.out.println(listNode);*/

        ListNode head = ListNode.of(7, 7, 7, 7);
        System.out.println(head);
        ListNode listNode = removeElements(head, 7);
        System.out.println(listNode);
    }
}
